package lib

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

// RemoveDuplicates 数组去重
func RemoveDuplicates(elements []string, defaultVal string) []string {
	encountered := map[string]bool{}
	var result []string

	for _, element := range elements {
		if !encountered[element] {
			encountered[element] = true
			result = append(result, element)
		}
	}

	//默认值
	if defaultVal != "" && len(result) == 0 {
		result = append(result, defaultVal)
	}

	return result
}

// GetMonthStartAndEnd 月份数据
func GetMonthStartAndEnd(monthStr string) (time.Time, time.Time, string, error) {
	if monthStr == "" {
		monthStr = time.Now().Format("2006-01")
	}
	parts := strings.Split(monthStr, "-")
	if len(parts) != 2 {
		return time.Time{}, time.Time{}, monthStr, fmt.Errorf("invalid format, expected YYYY-MM")
	}

	year, err := strconv.Atoi(parts[0])
	if err != nil {
		return time.Time{}, time.Time{}, monthStr, fmt.Errorf("invalid year: %v", err)
	}

	monthInt, err := strconv.Atoi(parts[1])
	if err != nil || monthInt < 1 || monthInt > 12 {
		return time.Time{}, time.Time{}, monthStr, fmt.Errorf("invalid month: %v", err)
	}

	month := time.Month(monthInt)

	// 获取指定月份的第一天
	start := time.Date(year, month, 1, 0, 0, 0, 0, time.Local)

	// 获取下个月的第一天，然后减去一秒得到当前月的最后一天
	end := start.AddDate(0, 1, 0).Add(-time.Second)

	return start, end, monthStr, nil
}

// IsLastDayOfMonth 是否为最后一天
func IsLastDayOfMonth(t time.Time) bool {
	// 获取明天的日期
	tomorrow := t.AddDate(0, 0, 1)
	// 如果明天的日期是下个月的第一天，则今天是本月的最后一天
	return tomorrow.Month() != t.Month()
}

// GetOrDefault 取值
func GetOrDefault(m interface{}, key string, defaultValue interface{}) interface{} {
	switch v := m.(type) {
	case map[string][]string:
		if values, ok := v[key]; ok {
			return values
		}
	case map[string]string:
		if value, ok := v[key]; ok {
			return value
		}
	case []string:
		if i, err := strconv.Atoi(key); err == nil && i < len(v) {
			return v[i]
		}
	}
	return defaultValue
}
